package de.slothsoft.commons.io;

import java.io.File;
import java.io.FileFilter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherFileFilter implements FileFilter {

	private boolean directoriesAllowed;
	private String[] expressions;
	private Pattern[] patterns;

	/**
	 * Expressions might contain * for any characters
	 * 
	 * @param expressions
	 */

	public MatcherFileFilter(String... expressions) {
		this(true, expressions);
	}

	public MatcherFileFilter(boolean directoriesAllowed, String... expressions) {
		this.expressions = expressions;
		this.directoriesAllowed = directoriesAllowed;
		makeExpressionsSuitableForMatcher();
	}

	private void makeExpressionsSuitableForMatcher() {
		// TODO might be a good idea to only allow the same characters as the os
		// does

		this.patterns = new Pattern[this.expressions.length];

		for (int i = 0; i < this.expressions.length; i++) {
			this.expressions[i] = this.expressions[i].toLowerCase().replace(
					"*", "(.*)");
			this.patterns[i] = Pattern.compile("^" + this.expressions[i] + "$");
		}
	}

	@Override
	public boolean accept(File file) {
		if (file.isDirectory() && this.directoriesAllowed) {
			return true;
		}

		String fileName = file.toString().toLowerCase();

		for (Pattern p : this.patterns) {
			Matcher mat = p.matcher(fileName);
			if (mat.find()) {
				return true;
			}
		}

		return false;
	}

	public boolean isDirectoriesAllowed() {
		return this.directoriesAllowed;
	}

	public void setDirectoriesAllowed(boolean directoriesAllowed) {
		this.directoriesAllowed = directoriesAllowed;
	}

}
